package com.itcast.admin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itcast.admin.domain.CheckupGroup;
import com.itcast.admin.domain.CheckupItem;
import com.itcast.admin.domain.Setmeal;
import com.itcast.admin.domain.request.CreateItemReqDTO;
import com.itcast.admin.domain.request.ItemPageReqDTO;
import com.itcast.admin.domain.request.QueryEnableGroupAndItemReqDTO;
import com.itcast.admin.domain.request.UpdateItemReqDTO;
import com.itcast.admin.domain.response.ItemPageResDTO;
import com.itcast.admin.domain.response.QueryEnableGroupAndItemResDTO;
import com.itcast.admin.mapper.CheckupGroupMapper;
import com.itcast.admin.mapper.CheckupItemMapper;
import com.itcast.admin.mapper.SetmealMapper;
import com.itcast.admin.service.ICheckupGroupService;
import com.itcast.admin.service.ICheckupItemService;
import com.itcast.admin.service.ISetmealService;
import com.jzo2o.common.expcetions.BadRequestException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.mysql.utils.PageHelperUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 体检项 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-11-04
 */
@Service
public class CheckupItemServiceImpl extends ServiceImpl<CheckupItemMapper, CheckupItem> implements ICheckupItemService {

    @Autowired
    private ICheckupGroupService checkupGroupService;

    @Autowired
    private CheckupItemMapper checkupItemMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private ISetmealService setmealService;

    @Autowired
    private CheckupGroupMapper checkupGroupMapper;


    /**
     * 分页查询体检项
     *
     * @param itemPageReqDTO
     * @return
     */
    @Override
    public PageResult<ItemPageResDTO> pageQuery(ItemPageReqDTO itemPageReqDTO) {
        return PageHelperUtils.selectPage(itemPageReqDTO, () -> checkupItemMapper.pageQuery(itemPageReqDTO));
    }

    @Override
    @Transactional
    public void createCheckItem(CreateItemReqDTO createItemReqDTO) {
        CheckupItem checkupItem = BeanUtils.copyBean(createItemReqDTO, CheckupItem.class);
        CheckupGroup checkupGroup = checkupGroupService.lambdaQuery().eq(CheckupGroup::getId, createItemReqDTO.getCheckGroupId()).one();
        if (checkupGroup == null) {
            throw new BadRequestException("查询失败");
        }
        checkupItem.setCheckGroupName(checkupGroup.getGroupName());

        //判断体检项名称是否重复
        CheckupItem checkupItemDB = lambdaQuery().eq(CheckupItem::getItemName, createItemReqDTO.getItemName()).one();
        if (checkupItemDB != null) {
            throw new BadRequestException("该体检项已存在");
        }
        boolean save = save(checkupItem);
        if (!save) {
            throw new RuntimeException("保存失败");
        }
    }

    /**
     * 根据id查询体检项
     *
     * @param id
     */
    @Override
    public CheckupItem getItemById(Integer id) {
        CheckupItem checkupItem = lambdaQuery().eq(CheckupItem::getId, id).one();
        if (checkupItem == null) {
            throw new BadRequestException("查询失败");
        }
        return checkupItem;
    }

    /**
     * 根据id修改体检项
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public void updateItemById(Integer id, UpdateItemReqDTO updateItemReqDTO) {
        CheckupGroup checkupGroup = checkupGroupService.lambdaQuery().eq(CheckupGroup::getId, updateItemReqDTO.getCheckGroupId()).one();
        if (checkupGroup == null) {
            throw new BadRequestException("查询失败");
        }
        //判断名称是否重复
        CheckupItem checkupItemDB = lambdaQuery().eq(CheckupItem::getItemName, updateItemReqDTO.getItemName())
                .ne(CheckupItem::getId, id).one();
        if (checkupItemDB != null) {
            throw new BadRequestException("该体检项已存在");
        }
        //判断价格或所属体检组是否发生修改
        CheckupItem checkupItem = lambdaQuery().eq(CheckupItem::getId, id).one();
        if (checkupItem.getItemPrice() != updateItemReqDTO.getItemPrice() || checkupItem.getCheckGroupId() != updateItemReqDTO.getCheckGroupId()) {
            //根据itemId 查询套餐ids
            List<Integer> setmealIds = checkupItemMapper.getSetMealIdsByItemId(id);
            if (setmealIds != null && setmealIds.size() > 0){
                //删除套餐关联的体检项
                checkupItemMapper.deleteItemAtSetmeal(id);

                //禁用关联套餐
                setmealMapper.disableSetmeals(setmealIds);

                //更新套餐价格
                for (Integer setmealId : setmealIds) {
                    //查询关联套餐中关联的检查项ids
                    List<Integer> itemIds = checkupGroupMapper.getItemIdsBySetmealId(setmealId);
                    //查询建议总价
                    BigDecimal totalPrice = checkupItemMapper.getTotalPrice(itemIds);
                    //更新价格
                    setmealService.lambdaUpdate().set(Setmeal::getSetmealCost, totalPrice).eq(Setmeal::getId, setmealId).update();
                }
            }
        }

        //完成修改
        boolean update = lambdaUpdate()
                .set(CheckupItem::getItemDescription, updateItemReqDTO.getItemDescription())
                .set(CheckupItem::getItemName, updateItemReqDTO.getItemName())
                .set(CheckupItem::getItemPrice, updateItemReqDTO.getItemPrice())
                .set(CheckupItem::getItemSex, updateItemReqDTO.getItemSex())
                .set(CheckupItem::getTargetConsumer, updateItemReqDTO.getTargetConsumer())
                .set(CheckupItem::getUnit, updateItemReqDTO.getUnit())
                .set(CheckupItem::getCheckGroupName, checkupGroup.getGroupName())
                .set(CheckupItem::getCheckGroupId, updateItemReqDTO.getCheckGroupId())
                .eq(CheckupItem::getId, id).update();
        if (!update) {
            throw new BadRequestException("修改失败");
        }
    }

    /**
     * 启用体检项
     *
     * @param id
     */
    @Override
    public void enableItemById(Integer id) {
        boolean update = lambdaUpdate().set(CheckupItem::getItemStatus, 1)
                .eq(CheckupItem::getId, id)
                .update();
        if (!update) {
            throw new BadRequestException("启用失败");
        }
    }

    /**
     * 校验更新操作会影响下架的套餐
     *
     * @param id
     */
    @Override
    public List<String> checkModifyById(Integer id) {
        return setmealMapper.checkModifyById(id);
    }

    /**
     * 校验禁用操作会影响下架的套餐
     *
     * @param id
     * @return
     */
    @Override
    public List<String> checkDisableById(Integer id) {
        return setmealMapper.checkModifyById(id);
    }

    /**
     * 根据id禁用体检项
     *
     * @param id
     */
    @Override
    @Transactional
    public void disableItemById(Integer id) {
        //禁用查询关联套餐ids
        List<Integer> setmealIds = checkupItemMapper.getSetMealIdsByItemId(id);
        if(setmealIds != null && setmealIds.size() > 0){
            //禁用有关联的套餐
            setmealMapper.disableSetmeals(setmealIds);

            //从关联表中删除数据
            checkupItemMapper.deleteItemAtSetmeal(id);
            //更新关联套餐价格
            for (Integer setmealId : setmealIds) {
                //查询关联套餐中关联的检查项ids
                List<Integer> itemIds = checkupGroupMapper.getItemIdsBySetmealId(setmealId);
                BigDecimal totalPrice = BigDecimal.ZERO;
                if (!(itemIds.size() == 0)) {
                    //查询建议总价
                    totalPrice = checkupItemMapper.getTotalPrice(itemIds);
                }
                //更新价格
                setmealService.lambdaUpdate().set(Setmeal::getSetmealCost, totalPrice).eq(Setmeal::getId, setmealId).update();
            }
        }

        //禁用体检项
        boolean update = lambdaUpdate().set(CheckupItem::getItemStatus, 2)
                .eq(CheckupItem::getId, id)
                .update();
        if (!update) {
            throw new BadRequestException("禁用失败");
        }
    }

    /**
     * 根据id删除体检项
     *
     * @param id
     */
    @Override
    public void deleteItemById(Integer id) {
        CheckupItem checkupItem = lambdaQuery().eq(CheckupItem::getId, id).one();
        if (checkupItem == null) {
            throw new BadRequestException("体检项不存在");
        }
        if (!(checkupItem.getItemStatus() == 0)) {
            throw new BadRequestException("状态有误,不能删除!");
        }
        boolean removeById = removeById(id);
        if (!removeById) {
            throw new BadRequestException("删除失败");
        }
    }

    /**
     * 查询启用的体检组和体检项
     *
     * @param queryEnableGroupAndItemReqDTO
     * @return
     */
    @Override
    public List<QueryEnableGroupAndItemResDTO> queryEnabledGroupAndItem(QueryEnableGroupAndItemReqDTO queryEnableGroupAndItemReqDTO) {
        return checkupItemMapper.queryEnabledGroupAndItem(queryEnableGroupAndItemReqDTO);
    }

    /**
     * 查询套餐id关联的检查项id列表
     *
     * @param id
     * @return
     */
    @Override
    public List<Integer> queryItemIdsBySetmealId(Integer id) {
        return checkupGroupMapper.getItemIdsBySetmealId(id);
    }
}
